<script setup>
import {ref, onMounted} from "vue";
import categoryApi from "../api/category.js";

const categories = ref([])
const newCategory = ref({categoryName:''})
const editCategory = ref(null)

const getCategories = async () => {
  categories.value = await categoryApi.getList()
}

const addCategory = async () => {
  if(!newCategory.value.categoryName) return
  await categoryApi.add(newCategory.value)
  newCategory.value.categoryName = ''
  getCategories()
}

const deleteCategory = async (id) => {
  await categoryApi.delete(id)
  getCategories()
}

const startEdit = (category) => {
  editCategory.value = {...category}
}

const updateCategory = async () => {
  if(!editCategory.value.categoryName) return
  await categoryApi.update(editCategory.value)
  editCategory.value = null
  getCategories()
}

onMounted(() => {
  getCategories()
})

</script>

<template>
<div>
  <h2>分类管理</h2>
<!--  添加分类-->
  <input v-model="newCategory.categoryName" placeholder="请输入分类名称" />
  <button @click="addCategory">添加</button>
<!--分类列表-->
<ul>
  <li v-for="c in categories" :key="c.categoryId">
      <span>{{c.categoryName}}</span>
      <button @click="startEdit(c)">编辑</button>
      <button @click="deleteCategory(c.categoryId)">删除</button>
  </li>
</ul>
  <!--  编辑分类-->
<div v-if="editCategory">
  <h3>编辑分类</h3>
  <input v-model="editCategory.categoryName"/>
  <button @click="updateCategory">保存</button>
  <button @click="editCategory = null">取消</button>
</div>


</div>
</template>

<style scoped>
h2 {
  margin-bottom: 10px;
}
input {
  margin-right: 5px;
}
button {
  margin-left: 5px;
}
</style>